package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.service.DevService;
import com.b511.swpu.cementbackend.entity.MetaField;
import com.b511.swpu.cementbackend.entity.MetaTable;
import com.b511.swpu.cementbackend.repository.MetaFieldRepository;
import com.b511.swpu.cementbackend.repository.MetaTableRepository;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

@Service
public class DevServiceImpl implements DevService {

    final EntityManager entityManager;

    final MetaTableRepository metaTableRepository;

    final MetaFieldRepository metaFieldRepository;

    public DevServiceImpl(EntityManager entityManager, MetaTableRepository metaTableRepository, MetaFieldRepository metaFieldRepository) {
        this.entityManager = entityManager;
        this.metaTableRepository = metaTableRepository;
        this.metaFieldRepository = metaFieldRepository;
    }

    @Override
    public void initTableAndField() {
        List<String> tableNames = getTablesName();
        for (String tableName : tableNames) {
            MetaTable table = metaTableRepository.findByTableName(tableName);
            if (null == table) {
                List<MetaField> fields = getMetaFields(tableName);
                saveTable(tableName, fields);
            }
        }
    }

    private List<String> getTablesName() {
        String queryTableSql = "select table_name from user_tables";
        Query queryTable = entityManager.createNativeQuery(queryTableSql);
        return queryTable.getResultList();
    }

    private List<MetaField> getMetaFields(String tableName) {
        String queryFieldSql = "SELECT column_name as filedName,data_type as fieldType,nullable as isNull from user_tab_columns WHERE table_name = ?";
        Query queryField = entityManager.createNativeQuery(queryFieldSql);
        queryField.setParameter(1, tableName);
        return analysisFieldData(queryField.getResultList());
    }


    private List<MetaField> analysisFieldData(List list) {
        List<MetaField> result = Lists.newArrayList();
        for (Object row : list) {
            Object[] cells = (Object[]) row;
            MetaField metaField = new MetaField();
            metaField.setFiledName((String) cells[0]);
            metaField.setFieldType((String) cells[1]);
            metaField.setNotNull(cells[2] == "N");
            result.add(metaField);
        }
        return result;
    }

    private void saveTable(String tableName, List<MetaField> fields) {
        MetaTable metaTable = new MetaTable();
        metaTable.setTableName(tableName);
        metaTable.setMetaFields(fields);
        metaTableRepository.save(metaTable);
    }
}
